package model

import "server/common"

type Project struct {
	Model
	Name string `gorm:"column:name;not null;type:varchar(50);unique" json:"name"`

	Users []Owner `gorm:"many2many:user_project;ForeignKey:ID;References:ID" json:"users"`
}

func (project *Project) TableName() string {
	return "project"
}

func (project *Project) List() ([]Project, int64) {
	project_list := []Project{}
	var count int64
	if err := common.DB.Preload("Users").Find(&project_list).Count(&count); err != nil {
		return project_list, count

	}
	return project_list, count
}

func (project *Project) Create() error {
	if err := common.DB.Create(&project).Error; err != nil {
		return err
	}
	return nil
}

func (project *Project) Update() error {
	if err := common.DB.Updates(&project); err != nil {
		return err.Error
	}
	return nil
}

func (project *Project) Delete() error {
	if err := common.DB.Delete(&project); err != nil {
		return err.Error
	}
	return nil
}

func (project *Project) AddUser() error {
	if err := common.DB.Debug().Model(&project).Where("id = ?", project.ID).Omit("Users.*").Association("Users").Append(&project.Users); err != nil {
		return err
	}
	return nil
}

func (project *Project) RemoveUser() error {
	if err := common.DB.Debug().Model(&project).Association("Users").Delete(&project.Users); err != nil {
		return err
	}
	return nil
}

func (project *Project) ListUser() []Owner {
	project_list := Project{}
	if err := common.DB.Preload("Users").Where("id = ?", project.ID).First(&project_list); err != nil {
		return project_list.Users

	}
	return project_list.Users
}
